//
//  ExploreVC.m
//  echo
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 Danny. All rights reserved.
//

#import "ExploreVC.h"
#import "NetworkingHandler.h"
#import "ModelForScrollView.h"
#import "CellForExploreSectionZero.h"
#import "ModelForExploreCollectionView.h"
#import "CellForExploreSectionOne.h"
#import "ModelForExploreTableViewCell.h"
#import "SearchVC.h"
#import <MJRefresh/MJRefresh.h>
#import <DKNightVersion.h>
#import "MusicPlayerVC.h"
#import "VCOfCellForExploreSectionOne.h"

@interface ExploreVC ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *arrForCollectionView;
@property (nonatomic, retain)NSMutableArray *tempArr;
@property (nonatomic, retain)NSMutableArray *arrForTableViewCell;
@property (nonatomic, retain)UIButton *buttonForSearch;
@property (nonatomic, assign)NSInteger i;
@end

@implementation ExploreVC

- (void)dealloc{
    [_arrForCollectionView release];
    [_tempArr release];
    [_arrForTableViewCell release];
    [_buttonForSearch release];
    self.tableView.delegate = nil;
    [_tableView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.i = 1;
    self.navigationItem.hidesBackButton = YES;
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"passModelForLeftButton" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        ModelForExploreTableViewCell *model = [note.userInfo objectForKey:@"model"];
        VCOfCellForExploreSectionOne *vc = [[VCOfCellForExploreSectionOne alloc]init];
        vc.id = model.id;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"passModelForRightButton" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        ModelForExploreTableViewCell *model = [note.userInfo objectForKey:@"model"];
        VCOfCellForExploreSectionOne *vc = [[VCOfCellForExploreSectionOne alloc]init];
        vc.id = model.id;
        [self.navigationController pushViewController:vc animated:YES];

    }];
}

- (void)handleDataForScrollViewImage{
    [NetworkingHandler networkingGetWithUrl:@"http://echosystem.kibey.com/index/banner?position=8" dicForValue:@{@"User-Agent":@"echo ios 1.0 20151114;(iPhone,iPhone OS8.3);IDFA F37139C2-85EF-45C8-B64D-2D16D2772A96 Paros/3.2.13"}  completeHandle:^(id result) {

         NSArray *arr = [result objectForKey:@"result"];
         self.arr = [NSMutableArray array];
         for (NSDictionary *dic in arr) {
             ModelForScrollView *model = [[ModelForScrollView alloc]init];
             [model setValuesForKeysWithDictionary:dic];
             [self.arr addObject:model];
             [model release];
         }
        
         [self.arr addObject:[self.arr firstObject]];
         [self.arr insertObject:[self.arr objectAtIndex:self.arr.count - 2] atIndex:0];
        [self createScrollView];
    }];
    
}

- (void)handleDataForCollectionViewItem{
    
    [NetworkingHandler networkingGetWithUrl:@"http://echosystem.kibey.com/channel/category?android_v=89&app_channel=_360&t=1453900838801&v=9&version=" completeHandle:^(id result) {

        NSDictionary *dic = [result objectForKey:@"result"];
        NSArray *arr = [dic objectForKey:@"data"];
        NSDictionary *dic2 = [arr objectAtIndex:0];
        NSArray *arr2 = [dic2 objectForKey:@"children"];

        self.arrForCollectionView = [NSMutableArray array];
        for (NSDictionary *tempDic in arr2) {
            ModelForExploreCollectionView *model = [[ModelForExploreCollectionView alloc]init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.arrForCollectionView addObject:model];
            [model release];
        }
        [self handleDataForTableViewCell];
    }];
}

- (void)handleDataForTableViewCell{

    [NetworkingHandler networkingGetWithUrl:@"http://echosystem.kibey.com/channel/get?with_sound=0&order=hot&page=1" dicForValue:@{@"x-v":@"20160209",@"x-c":@"3"} completeHandle:^(id result) {
        self.tempArr = [NSMutableArray array];
        if (!self.arrForTableViewCell) {
            
            self.arrForTableViewCell = [NSMutableArray array];
            
        }
        NSDictionary *dic = [result objectForKey:@"result"];
        NSArray *arr = [dic objectForKey:@"data"];
        for (NSDictionary *tempDic in arr) {
            ModelForExploreTableViewCell *model = [[ModelForExploreTableViewCell alloc]init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.tempArr addObject:model];
            [model release];
        }
        for (int i = 0; i < self.tempArr.count; i++) {
            if (i%2 == 0) {
                NSMutableArray *arrForCell = [NSMutableArray array];
                [arrForCell addObject:self.tempArr[i]];
                [arrForCell addObject:self.tempArr[i+1]];
                [self.arrForTableViewCell addObject:arrForCell];
            }
            
        }
        [self.tableView reloadData];
        [self createTableView];
    }];
}

- (void)createScrollView{
    [super createScrollView];
    [self handleDataForCollectionViewItem];
}

- (void)createTableView{
    if (!self.tableView) {
        
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 76) style:UITableViewStyleGrouped];
        [self.view addSubview:self.tableView];
        [self.tableView release];
        
    }
    self.tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:17 / 256.f green:27 / 256.f blue:47 / 256.f alpha:1]);
    self.tableView.tableHeaderView = self.backView;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.tableView registerClass:[CellForExploreSectionZero class] forCellReuseIdentifier:@"poolForCellOfSectionZero"];
    
    [self.tableView registerClass:[CellForExploreSectionOne class] forCellReuseIdentifier:@"poolForCellOfSectionOne"];
    
    self.buttonForSearch = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.navigationController.navigationBar addSubview:self.buttonForSearch];
    self.buttonForSearch.frame = CGRectMake(15 * WIDTH, 2.5 * HEIGHT, 35 * WIDTH, 35 * WIDTH);
    [self.buttonForSearch setBackgroundImage:[UIImage imageNamed:@"iconfont-search"] forState:UIControlStateNormal];
    [self.buttonForSearch addTarget:self action:@selector(handleSearch) forControlEvents:UIControlEventTouchUpInside];
    [self handleRefresh];

}

- (void)handleSearch{
    SearchVC *searchVC = [[SearchVC alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
//    [searchVC release];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
      
        return 45 * HEIGHT;
    }else{
        
        return 50 * HEIGHT;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 2;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        
        UIView *viewForHeader1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45 * HEIGHT)];
        viewForHeader1.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:218 / 255.f green:219 / 255.f blue:216 / 255.f alpha:1], [UIColor colorWithRed:17 / 256.f green:27 / 256.f blue:47 / 256.f alpha:1]);
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 10 * HEIGHT, self.view.frame.size.width, 30 * HEIGHT)];
        label1.text = @"     频道分类";
        label1.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor whiteColor]);
        [viewForHeader1 addSubview:label1];
        [label1 release];
        
        return viewForHeader1;
    }else{
        
        UIView *viewForHeader2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50 * HEIGHT)];
        viewForHeader2.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:218 / 255.f green:219 / 255.f blue:216 / 255.f alpha:1], [UIColor colorWithRed:17 / 256.f green:27 / 256.f blue:47 / 256.f alpha:1]);
        UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 15 * HEIGHT, self.view.frame.size.width, 30 * HEIGHT)];
        label2.text = @"     全部频道";
        label2.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor whiteColor]);
        [viewForHeader2 addSubview:label2];
        [label2 release];
        
        return viewForHeader2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
        
    }else{
        
        return self.arrForTableViewCell.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        CellForExploreSectionZero *cell1 = [tableView dequeueReusableCellWithIdentifier:@"poolForCellOfSectionZero"];
      
        [cell1 passDataArrForCollectionView:self.arrForCollectionView];
        [cell1 setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell1;
    }else{

        CellForExploreSectionOne *cell2 = [tableView dequeueReusableCellWithIdentifier:@"poolForCellOfSectionOne"];
        NSArray *arr = [self.arrForTableViewCell objectAtIndex:indexPath.row];
            
        [cell2 passModelForTableViewCell:arr];
        [cell2 setSelectionStyle:UITableViewCellSelectionStyleNone];

        return cell2;
    }
 
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {

        return (self.view.frame.size.width - 10 * WIDTH - 15 * WIDTH * 5)/5 + 21.2 * HEIGHT;
    }else{
        return 110 * HEIGHT;
    }
}

- (void)handleRefresh{ 
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.i = 1;
            self.tempArr = [NSMutableArray array];
            self.arrForTableViewCell = [NSMutableArray array];
            [self handleDataForScrollViewImage];
            
            [self.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
            
        });
    }];
    
   self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSString *str = [NSString stringWithFormat:@"http://echosystem.kibey.com/channel/get?with_sound=0&order=hot&page=%ld", (long)(1 + self.i++)];
            [NetworkingHandler networkingGetWithUrl:str dicForValue:@{@"x-v":@"20160209",@"x-c":@"3"} completeHandle:^(id result) {
                NSDictionary *dic = [result objectForKey:@"result"];
                NSArray *arr = [dic objectForKey:@"data"];
                self.tempArr = [NSMutableArray array];
                for (NSDictionary *tempDic in arr) {
                    ModelForExploreTableViewCell *model = [[ModelForExploreTableViewCell alloc]init];
                    [model setValuesForKeysWithDictionary:tempDic];
                    [self.tempArr addObject:model];
                    [model release];
                }
                for (int i = 0; i < self.tempArr.count; i++) {
                    if (i%2 == 0) {
                        NSMutableArray *arrForCell = [NSMutableArray array];
                        [arrForCell addObject:self.tempArr[i]];
                        [arrForCell addObject:self.tempArr[i+1]];
                        [self.arrForTableViewCell addObject:arrForCell];
                    }
                }
                [self.tableView reloadData];
            }];
            [self.tableView.mj_footer endRefreshing];
        });
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

//     [self.arrForTableViewCell objectAtIndex:indexPath.row];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:17 / 256.f green:27 / 256.f blue:47 / 256.f alpha:1]);
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName : [UIFont fontWithName:@"Arial" size:17]}];
    } else {
        
        [DKNightVersionManager dawnComing];
        [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor blackColor],NSFontAttributeName : [UIFont fontWithName:@"Arial" size:17]}];
    }
    self.tabBarController.tabBar.dk_barTintColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:18 / 256.f green:29 / 256.f blue:50 / 256.f alpha:1]);
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
